package com.seo.service.user.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.seo.mapper.user.ConfigMapper;
import com.seo.mapper.user.UserDomainMapper;
import com.seo.mapper.user.UserMapper;
import com.seo.mapper.user.role.UserRoleMapper;
import com.seo.pojo.ReturnBody;
import com.seo.service.sms.sdk.SmsCodeService;
import com.seo.service.user.sdk.UserService;
import com.seo.utils.DataUtil;
import com.seo.utils.Jurisdiction;
import com.seo.utils.PatternTool;

import cn.hutool.core.lang.PatternPool;
import cn.hutool.core.util.ReUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Autowired
	private UserDomainMapper userDomainMapper;

	@Autowired
	private SmsCodeService smsCodeService;

	@Autowired
	private ConfigMapper configMapper;

	@Transactional(readOnly = true)
	@Override
	public ReturnBody login(int domainUserId, String userName, String password, String code) {
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = userMapper.getUserByUserName(userName);
		if (user == null || user.isEmpty()) {
			return rb.error("error", "用户不存在");
		}
		String state = (String) user.get("state");
		if (!"01".equals(state)) {
			return rb.error("error", "用户被禁用");
		}

		String realPassword = (String) user.get("password");

		String inputPassword = SecureUtil.md5(password);
		if (!inputPassword.equals(realPassword)) {
			return rb.error("error", "输入密码错误");
		}
		int userId = (int) user.get("id");
		int parentId = (int) user.get("parentId");
		if (domainUserId == 0) {
			if (parentId > 0) {
				log.error("二级以上用户不能通过顶级域名访问[{}]", userId);
				return rb.error("error", "用户不存在");
			}
		} else {

			if (parentId == 0) {
				if (userId != domainUserId) {
					log.error("一级用户访问域名错误[{}]", userId);
					return rb.error("error", "用户不存在");
				}
			} else {

				String roleCode = (String) user.get("roleCode");
				if ("proxy".equals(roleCode)) {
					
					if (userId != domainUserId) {
						Map<Integer, Map<String,Object>> idMap = userMapper.getUserParentId(parentId);
						if(idMap == null || !idMap.containsKey(domainUserId)) {
							log.error("二级以上代理用户访问域名错误[{}]", userId);
							return rb.error("error", "用户不存在");
						}
					}

				} else {
					Map<Integer, Map<String,Object>> idMap = userMapper.getUserParentId(parentId);
					if(idMap == null || !idMap.containsKey(domainUserId)) {
						log.error("二级以上用户访问域名错误[{}]", userId);
						return rb.error("error", "用户不存在");
					}
				}

			}
		}

		rb.put("user", user);

		return rb.success();
	}

	@Transactional
	@Override
	public ReturnBody register(int domainUserId, String userName, String password, String againPassword, String phone,
			String smsCode, String sInviteCode) {
		ReturnBody rb = ReturnBody.init();
		try {
			if (domainUserId > 0) {
				Map<String, Object> parentUser = userMapper.getUserById(domainUserId);
				String roleCode = (parentUser.get("roleCode") != null) ? (String) parentUser.get("roleCode") : "";
				if (!"proxy".equals(roleCode)) {
					return rb.error("error", "未开通注册功能，请联系管理员");
				}
			}
			userName = StringUtils.trim(userName);
			if (StringUtils.isEmpty(userName)) {
				return rb.error("error", "请设置用户名");
			}

			if (userName.length() < 3 || userName.length() > 20) {
				return rb.error("error", "用户名最短3位，最长20位");
			}

			if (!ReUtil.contains(PatternTool.USER_NAME, userName)) {
				return rb.error("error", "用户名只能包含英文或数字");
			}

			password = StringUtils.trim(password);
			if (StringUtils.isEmpty(password)) {
				return rb.error("error", "请设置登录密码");
			}

			againPassword = StringUtils.trim(againPassword);
			if (StringUtils.isEmpty(againPassword)) {
				return rb.error("error", "请再次确认密码");
			}

			if (!password.equals(againPassword)) {
				return rb.error("error", "两次密码输入不一致");
			}

			phone = StringUtils.trim(phone);
			if (StringUtils.isEmpty(phone)) {
				return rb.error("error", "手机号不能为空");
			}

			if (!ReUtil.contains(PatternPool.MOBILE, phone)) {
				log.error("手机号格式错误");
				return rb.error("请输入正确手机号");
			}

			smsCode = StringUtils.trim(smsCode);

			if (StringUtils.isEmpty(smsCode)) {
				return rb.error("smsCode", "验证码不能为空");
			}

			Map<String, Object> user = userMapper.getUserByUserName(userName);
			if (user != null) {
				log.error("该用户名已注册-[{}]", userName);
				return rb.error("该用户名已注册");
			}

			user = userMapper.getUserByPhone(phone);
			if (user != null) {
				log.error("该手机已注册-[{}]", phone);
				return rb.error("该手机已注册");
			}
			Map<String, Object> params = new HashMap<>();
			params.put("phone", phone);
			params.put("type", "register");
			params.put("code", smsCode);
			rb.run(smsCodeService.updateValidateCode(params));
			if (!rb.isSuccess()) {
				return rb;
			}

			params.put("parentId", domainUserId);
			params.put("userName", userName);
			params.put("phone", phone);
			params.put("creditValue", 0);
			params.put("roleId", userRoleMapper.getRoleByCode("init").get(0).get("id"));
			params.put("password", SecureUtil.md5(password));
			params.put("state", "01");
			if (StringUtils.isNotEmpty(sInviteCode)) {
				Map<String, Object> sysUser = userMapper.getSysUserByInviteCode(sInviteCode);
				if (sysUser != null) {
					params.put("belongId", sysUser.get("id"));
				}
			}

			int num = userMapper.addUser(params);
			if (num == 0) {
				return rb.rollback("注册失败");
			}
			//rb.put("domain", getDomain(userName, 0, null));
			return rb.success("ok", "注册成功");
		} catch (Exception e) {
			log.error("异常-[{}]", e);
			return rb.error("注册失败");
		} finally {
			rb.result();
		}
	}

	@Override
	public String getDomain(String userName, int userId, String state) {
		List<Map<String, Object>> domainList = null;
		if (userId > 0) {
			Map<String, Object> params = new HashMap<>();
			params.put("userId", userId);
			params.put("state", state);
			domainList = userDomainMapper.getUserDomainByUserId(params);
		}
		String domain = "";
		if (domainList != null && domainList.size() > 0) {
			Map<String, Object> userDomain = domainList.get(0);
			domain = (String) userDomain.get("domain");
		} else {
			domain = userName + "." + configMapper.getConfig("domain");
		}

		String port = configMapper.getConfig("seo-port");
		if (StringUtils.isNotEmpty(port) && !"80".equals(port)) {
			domain += ":" + port;
		}
		return domain;
	}

	@Override
	public ReturnBody getUserByName(String userName) {
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = userMapper.getUserByUserName(userName);
		if (user == null) {
			return rb.error("error", "用户不存在");
		}
		String state = (String) user.get("state");
		if (!"01".equals(state)) {
			return rb.error("error", "用户被禁用");
		}
		rb.put("user", user);
		rb.put("userId", user.get("id"));
		return rb.success();
	}

	@Override
	public ReturnBody getCheckUserByDomain(String domain) {
		ReturnBody rb = ReturnBody.init();
		String sysDomain = "." + configMapper.getConfig("domain");
		if (domain.endsWith(sysDomain)) {
			log.info("内部二级域名-[{}]", domain);
			String userName = domain.replace(sysDomain, "");
			Map<String, Object> user = userMapper.getUserByUserName(userName);
			if (user == null) {
				log.error("用户不存在-[{}]", domain);
				return rb.error("您访问的网站尚未开通");
			}
			String state = (String) user.get("state");
			if (!"01".equals(state)) {
				log.error("用户被禁用-[{}]", domain);
				return rb.error("您访问的网站尚未开通");
			}
			Integer parentId = (Integer) user.get("parentId");

			if (parentId > 0) {
				log.error("只有顶级用户可以访问二级域名-[{}]", domain);
				return rb.error("您访问的网站尚未开通");
			}

			rb.put("user", user);
			return rb.success();
		} else {
			log.info("外部域名-[{}]", domain);
			Map<String, Object> userDomain = userDomainMapper.getUserDomainByDomain(domain);
			if (userDomain == null) {
				log.error("外部域名不存在-[{}]", domain);
				return rb.error("您访问的网站尚未开通");
			}
			String domainState = (String) userDomain.get("state");
			if (!"01".equals(domainState)) {
				log.error("外部域名已禁用-[{}]", domain);
				return rb.error("您访问的网站已禁用");
			}

			int userId = (int) userDomain.get("userId");
			Map<String, Object> user = userMapper.getUserById(userId);
			if (user == null) {
				log.error("用户不存在-[{}]", domain);
				return rb.error("您访问的网站尚未开通");
			}
			String state = (String) user.get("state");
			if (!"01".equals(state)) {
				log.error("用户被禁用-[{}]", domain);
				return rb.error("您访问的网站尚未开通");
			}
			rb.put("user", user);
			return rb.success();
		}
	}

	@Override
	public List<Map<String, Object>> getUserList(Map<String, Object> params) {
		return userMapper.getUserList(params);
	}

	@Override
	public Map<String, Object> getUserByPhone(String phone) {
		return userMapper.getUserByPhone(phone);
	}

	@Override
	public ReturnBody saveRegisterSmsCode(String phone) {
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = userMapper.getUserByPhone(phone);
		if (user != null) {
			log.error("该手机已注册-[{}]", phone);
			return rb.error("该手机已注册");
		}
		Map<String, Object> params = new HashMap<>();
		params.put("phone", phone);
		params.put("type", "register");
		rb.run(smsCodeService.sendSmsCode(params));
		return rb;
	}

	@Override
	public Map<String, Object> getUserByInviteCode(String inviteCode) {

		return userMapper.getUserByInviteCode(inviteCode);
	}

	@Override
	public Map<String, Object> getUserById(Integer id) {
		return userMapper.getUserById(id);
	}

	@Override
	public Integer getUserCnt(Map<String, Object> params) {
		return userMapper.getUserCnt(params);
	}

	@Override
	public ReturnBody addUser(Map<String, Object> params) {
		ReturnBody rb = ReturnBody.init();
		try {
			if (!params.containsKey("roleId")) {
				return rb.error("请选择角色");
			}
			String roleId = (String) params.get("roleId");
			if (StringUtils.isEmpty(roleId)) {
				return rb.error("请选择角色");
			}

			if (!params.containsKey("userName")) {
				return rb.error("请输入账号");
			}
			String userName = StringUtils.trim((String) params.get("userName"));
			if (StringUtils.isEmpty(userName)) {
				return rb.error("请输入账号");
			}

			if (userName.length() < 3 || userName.length() > 20) {
				return rb.error("error", "用户名最短3位，最长20位");
			}

			if (!ReUtil.contains(PatternTool.USER_NAME, userName)) {
				return rb.error("error", "用户名只能包含英文或数字");
			}

			if (!params.containsKey("petName")) {
				return rb.error("请输入昵称");
			}
			String petName = (String) params.get("petName");
			if (StringUtils.isEmpty(petName)) {
				return rb.error("请输入昵称");
			}

			if (!params.containsKey("password")) {
				return rb.error("请输入密码");
			}
			String password = (String) params.get("password");
			if (StringUtils.isEmpty(password)) {
				return rb.error("请输入密码");
			}

			if (!params.containsKey("phone")) {
				return rb.error("请输入手机号");
			}
			String phone = (String) params.get("phone");
			if (StringUtils.isEmpty(phone)) {
				return rb.error("请输入手机号");
			}

			if (!params.containsKey("email")) {
				return rb.error("请输入邮箱");
			}
			String email = (String) params.get("email");
			if (StringUtils.isEmpty(email)) {
				return rb.error("请输入邮箱");
			}

			if (!params.containsKey("creditValue")) {
				params.put("creditValue", 0);
			}

			params.put("password", SecureUtil.md5(password));
			params.put("state", "01");
			Integer createId = Jurisdiction.getT("id", Integer.class);
			params.put("belongId", createId);
			params.put("createId", createId);
			params.put("updateId", createId);
			int num = userMapper.addUser(params);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback("用户名或手机号重复");
		} finally {
			rb.result();
		}

	}

	@Override
	public ReturnBody deleteUser(Integer id) {
		ReturnBody rb = ReturnBody.init();
		int num = userMapper.deleteUser(id);
		if (num == 0) {
			return rb.error();
		}

		return rb.success();
	}

	@Override
	public ReturnBody deleteUserFalse(Integer id, String isDelete) {
		ReturnBody body = ReturnBody.init();

		try {
			Map<String, Object> params = new HashMap<>();
			params.put("id", id);
			params.put("isDelete", isDelete);
			Integer updateId = Jurisdiction.getT("id", Integer.class);
			params.put("updateId", updateId);
			int num = userMapper.updateUser(params);
			if (num == 0) {
				return body.rollback();
			}
			return body.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return body.rollback();
		} finally {
			body.result();
		}

	}

	@Override
	public ReturnBody updateUser(Map<String, Object> params) {

		ReturnBody rb = ReturnBody.init();
		try {
			if (!params.containsKey("id")) {
				return rb.error("用户不存在");
			}
			String id = (String) params.get("id");
			if (StringUtils.isEmpty(id)) {
				return rb.error("用户不存在");
			}
			String roleId = "";
			if (params.containsKey("roleId")) {
				roleId = (String) params.get("roleId");
				if (StringUtils.isEmpty(roleId)) {
					return rb.error("请选择角色");
				}
			}

			if (params.containsKey("petName")) {
				String petName = (String) params.get("petName");
				if (StringUtils.isEmpty(petName)) {
					return rb.error("请输入昵称");
				}
			}

			if (params.containsKey("phone")) {
				String phone = (String) params.get("phone");
				if (StringUtils.isEmpty(phone)) {
					return rb.error("请输入手机号");
				}
			}
			if (params.containsKey("email")) {
				String email = (String) params.get("email");
				if (StringUtils.isEmpty(email)) {
					return rb.error("请输入邮箱");
				}
			}

			if (!params.containsKey("creditValue")) {
				params.put("creditValue", 0);
			}

			if (params.containsKey("sex")) {
				String sex = (String) params.get("sex");
				if (StringUtils.isEmpty(sex)) {
					return rb.error("请选择性别");
				}
			}
			Integer updateId = Jurisdiction.getT("id", Integer.class);
			params.put("updateId", updateId);
			int num = userMapper.updateUser(params);
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}

	}

	@Override
	public ReturnBody updateTemplet(Map<String, Object> params) {
		ReturnBody rb = ReturnBody.init();
		try {
			if (!params.containsKey("id")) {
				return rb.error("用户不存在");
			}
			Integer id = (Integer) params.get("id");
			if (id == null || id <= 0) {
				return rb.error("用户不存在");
			}

			if (params.containsKey("templet")) {
				String templet = (String) params.get("templet");
				if (StringUtils.isEmpty(templet)) {
					return rb.error("请选择皮肤");
				}
			}
			Integer updateId = Jurisdiction.getT("id", Integer.class);
			params.put("updateId", updateId);
			int num = userMapper.updateUser(params);
			if (num == 0) {
				return rb.rollback();
			}

			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	@Override
	public ReturnBody updateUserState(Integer id, String state) {

		ReturnBody rb = ReturnBody.init();
		int num = userMapper.updateUserState(id, state);
		if (num == 0) {
			return rb.error();
		}

		return rb.success();
	}

	@Override
	public ReturnBody updateUserPwd(Map<String, Object> params) {
		ReturnBody rb = ReturnBody.init();
		if (!params.containsKey("oldPassword")) {
			return rb.error("请输入原始密码");
		}

		String oldPassword = (String) params.get("oldPassword");
		if (StringUtils.isEmpty(oldPassword)) {
			return rb.error("请输入原始密码");
		}

		if (!params.containsKey("password")) {
			return rb.error("请输入密码");
		}

		String password = (String) params.get("password");
		if (StringUtils.isEmpty(password)) {
			return rb.error("请输入密码");
		}

		if (!params.containsKey("confirmPassword")) {
			return rb.error("请再次确认密码");
		}

		String confirmPassword = (String) params.get("confirmPassword");
		if (StringUtils.isEmpty(confirmPassword)) {
			return rb.error("请再次确认密码");
		}

		if (!StringUtils.equals(confirmPassword, password)) {
			return rb.error("再次确认密码错误");
		}

		Integer id = (Integer) params.get("id");
		Map<String, Object> user = userMapper.getUserById(id);
		if (user == null) {
			return rb.error("用户不存在");
		}
		String dataPassword = (String) user.get("password");
		if (!dataPassword.equals(SecureUtil.md5(oldPassword))) {
			return rb.error("原始密码不正确");
		}

		params.put("password", SecureUtil.md5(password));

		int num = userMapper.updateUserPwd(params);
		if (num == 0) {
			return rb.error("重置密码失败");
		}
		return rb.success();
	}

	@Override
	public ReturnBody updateResetUserPwd(Map<String, Object> params) {
		ReturnBody rb = ReturnBody.init();
		Integer id = (Integer) params.get("id");
		Map<String, Object> user = userMapper.getUserById(id);
		if (user == null) {
			return rb.error("用户不存在");
		}

		if (!params.containsKey("password")) {
			return rb.error("请输入密码");
		}

		String password = (String) params.get("password");
		if (StringUtils.isEmpty(password)) {
			return rb.error("请输入密码");
		}

		params.put("password", SecureUtil.md5(password));
		int num = userMapper.updateUserPwd(params);
		if (num == 0) {
			return rb.error("重置密码失败");
		}
		return rb.success();
	}

	@Override
	public ReturnBody updateProxyPrice(Map<String, Object> params) {

		ReturnBody rb = ReturnBody.init();
		try {
			if (!params.containsKey("id")) {
				return rb.error("用户不存在");
			}
			String id = (String) params.get("id");
			if (StringUtils.isEmpty(id)) {
				return rb.error("用户不存在");
			}

			if (!params.containsKey("type")) {
				return rb.error("参数有误");
			}
			String type = (String) params.get("type");
			if (StringUtils.isEmpty(type)) {
				return rb.error("参数有误");
			}

			if (params.containsKey("price1")) {
				BigDecimal price1 = DataUtil.getBigDecimal(params.get("price1"));
				if (price1.compareTo(BigDecimal.ZERO) < 0) {
					return rb.error("代理价不能低于0");
				}

			}
			if (params.containsKey("price2")) {
				BigDecimal price2 = DataUtil.getBigDecimal(params.get("price2"));
				if (price2.compareTo(BigDecimal.ZERO) < 0) {
					return rb.error("代理价不能低于0");
				}

			}

			int num = 0;
			if ("00".equals(type)) {
				num = userMapper.updateUser(params);
			} else {
				if (params.containsKey("price2")) {
					BigDecimal price2 = DataUtil.getBigDecimal(params.get("price2"));
					if (price2.compareTo(BigDecimal.ZERO) < 0) {
						return rb.error("代理价不能低于0");
					}

				}

				if (params.containsKey("price3")) {
					BigDecimal price3 = DataUtil.getBigDecimal(params.get("price3"));
					if (price3.compareTo(BigDecimal.ZERO) < 0) {
						return rb.error("代理价不能低于0");
					}

				}
				num = userMapper.updateProxyUser(params);
			}
			if (num == 0) {
				return rb.rollback();
			}
			return rb.success();
		} catch (Exception e) {
			log.error("异常-{}", e);
			return rb.rollback();
		} finally {
			rb.result();
		}
	}

	@Override
	public Map<String, Object> getUserProxyById(int id) {
		return userMapper.getUserProxyById(id);
	}

	@Override
	public List<Map<String, Object>> getUserParent(Map<String, Object> user) {
		return userMapper.getUserParent(user);
	}

	@Override
	public Map<String, Object> getPriceToVipLevel(Map<String, Object> map) {
		return userMapper.getPriceToVipLevel(map);
	}

	@Override
	public Map<String, Object> getUserPriceToVipLevel(Map<String, Object> ma) {
		return userMapper.getUserPriceToVipLevel(ma);
	}

	@Override
	public int getUserPriceToVipLevelNum(int parseInt) {
		return userMapper.getUserPriceToVipLevelNum(parseInt);
	}

	@Override
	public ReturnBody saveProxyPrice(Map<String, Object> params) {
		ReturnBody rb = ReturnBody.init();
		if (params == null || params.isEmpty()) {
			return rb.error("缺少参数");
		}
		String roleId = params.get("roleId") + "";
		String userId = params.get("userId") + "";
		/*
		 * int num = userMapper.getUserPriceToVipLevelNum(Integer.parseInt(userId));
		 * if(num > 0) { return rb.error("该用户代理价已设置"); }
		 */
		Integer createId = Jurisdiction.getT("id", Integer.class);
		try {
			Map<String, Object> role = userRoleMapper.getRoleById(Integer.parseInt(roleId));
			if (role == null || role.isEmpty()) {
				return rb.rollback();
			}
			String code = (String) role.get("code");
			if ("proxy".equals(code)) {
				userMapper.deleteUserPriceLevel(userId);
				String[] serviceType = { "01", "02", "03" }; // 业务类型
				String[] userType = { "01", "02" };// 用户类型
				String[] vip;// vip等级V1-V6
				String vipLevel = configMapper.getConfig("vip_level");
				if (vipLevel != null && !"".equals(vipLevel)) {
					vip = vipLevel.split(",");
				} else {
					return rb.rollback("设置失败");
				}
				int num = 0;
				for (int i = 0; i < userType.length; i++) {
					for (int j = 0; j < serviceType.length; j++) {
						for (int x = 0; x < vip.length; x++) {
							Map<String, Object> pam = new HashMap<String, Object>();
							pam.put("userId", userId);
							pam.put("serviceType", serviceType[j]);
							pam.put("userType", userType[i]);
							pam.put("vip", vip[x]);
							pam.put("createId", createId);
							num = userMapper.addUserPriceLevel(pam);
							if (num == 0) {
								return rb.rollback();
							}
						}
					}
				}
			}
			rb.success();
		} catch (Exception e) {
			e.printStackTrace();
			rb.rollback("设置失败");
		} finally {
			rb.result();
		}
		return rb;
	}

}
